/*
 * @Author: CodeHare
 * @Date: 2023-10-13 13:40:19
 * @LastEditors: CodeHare
 * @LastEditTime: 2023-10-20 16:00:45
 * @Description: 用户信息页面
 */
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/pages/mine/user_info/user_info_model.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/user_entity_manager.dart';

class UserInfoController extends GetxController {
  final UserInfoModel model = UserInfoModel();
  bool isEnableEdit = false;
  String avatar = '';
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController mobileController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final _authServices = Get.put(AuthServices());
  UserModel ?userModel;
  @override
  void onReady() {
    _getUserDetails();
  }

  @override
  void onClose() {}
  void _getUserDetails() async {
    Configs.httpClient.requestWithLoading(() async {
      await _authServices.getUserInfo().then((value) {
        if(value !=null){
          userModel = UserModel.fromJson(value);
          userNameController.text = userModel!.nickName??'';
          mobileController.text = userModel!.phone??'';
          emailController.text = userModel!.email??'';
          avatar = userModel!.avatar??'';
          update();
        }

      });

    }, onError: (err) {
      // dismissLoading();
      handleException(err);
      return true;
    },showLoading: true);
  }
  edit(){
    isEnableEdit = true;
    if (emailController.text == '--') {
      emailController.text = '';
    }
    if (userNameController.text == '--') {
      userNameController.text = '';
    }
    if (mobileController.text == '--') {
      mobileController.text = '';
    }
    update();
  }
  save() async {
    var param = {
      'nickName': userNameController.text,
    };
    if(avatar.isNotEmpty){
      param['avatar'] = avatar;
    }

    if(emailController.text.isNotEmpty){
      param['email'] = emailController.text;
    }

    if(mobileController.text.isNotEmpty){
      param['phone'] = mobileController.text;
    }

  showLoading();
   var result = await _authServices.updateUserInfo(param,onError: (error){
     dismissLoading();
     handleException(error);
     return false;
   });
    dismissLoading();
    // if(result != null){
      Get.back(result: param);
    // }
  }
  cancel(){
    if (emailController.text.isEmpty) {
      emailController.text = '--';
    }
    if (userNameController.text.isEmpty) {
      userNameController.text = '--';
    }
    if (mobileController.text.isEmpty) {
      mobileController.text = '--';
    }
    isEnableEdit = false;
    update();
  }
}
